<template>
  <el-dialog
    :model-value="show"
    title="批量申请投放站点"
    :width="step === 2 ? '1340px' : '800px'"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :class="step === 2 ? 'vika-dialog' : ''"
    destroy-on-close
  >
    <DynamicsForm
      ref="DynamicsFormRef"
      form_uni_key="application_batch_apply_create_form_company"
      v-show="step === 1"
      :events="{ clearVika }"
    />
    <Vika
      ref="VikaRef"
      v-show="step === 2"
      :formValues="formValues"
      @clearVika="clearVika"
      @changeTotal="changeTotal"
    />

    <template #footer>
      <!-- 第一步特有 -->
      <el-button
        v-if="step === 1"
        type="primary"
        :loading="step1Loading"
        :disabled="!show"
        @click="toNext"
      >
        下一步
      </el-button>
      <!-- 第二步特有 -->
      <template v-if="step === 2">
        <!-- 提交 -->
        <el-button
          type="primary"
          :loading="step2Loading"
          :disabled="!show"
          @click="submitForm"
        >
          提交批量申请
        </el-button>
        <!-- 下一步 -->
        <el-button type="primary" :disabled="!show" @click="toPrev">
          上一步
        </el-button>
      </template>
      <el-button type="info" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import DynamicsForm from '@/components/DynamicsForm';
import Vika from './Vika';
import { companyApplicationBatchApply } from '@/api/resources';
import { ElMessageBox } from 'element-plus';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['success', 'update:show']);

const step = ref(1);
const DynamicsFormRef = ref();
const VikaRef = ref();
const step1Loading = ref(false);
const step2Loading = ref(false);
const needInitVika = ref(true);

// 关闭
function handleClose() {
  emit('update:show', false);
}

// 重新生成维格云表格
function clearVika() {
  step.value = 1;
  needInitVika.value = true;
}

// 下一步
const formValues = ref([]);
async function toNext() {
  try {
    step1Loading.value = true;
    formValues.value = await DynamicsFormRef.value.returnData();
    step1Loading.value = false;
    if (!needInitVika.value) {
      step.value = 2;
      return;
    }
    needInitVika.value = false;
    nextTick(() => {
      step1Loading.value = true;
      VikaRef.value
        .createTable()
        .then(() => {
          step.value = 2;
        })
        .finally(() => {
          step1Loading.value = false;
        });
    });
  } catch {
    step1Loading.value = false;
  }
}

// 上一步
async function toPrev() {
  step.value = 1;
}

// 返回维格云总条数
const tableTotal = ref(0);
function changeTotal(total) {
  tableTotal.value = total;
}

// 提交
async function submitForm() {
  try {
    step2Loading.value = true;
    const _form = await VikaRef.value.returnData();
    step2Loading.value = false;

    ElMessageBox({
      title: '批量申请投放站点确认',
      dangerouslyUseHTMLString: true,
      message: `请确认是否提交 <span style='color:var(--el-color-danger);font-weight:bold;'>${tableTotal.value}</span> 条申请？<br>确认申请后将根据填写内容生成多个投放站点申请信息`,
      type: 'warning',
      confirmButtonText: '确认申请',
      showCancelButton: true,
      beforeClose: (action, instance, done) => {
        if (action !== 'confirm') return done();
        instance.confirmButtonLoading = true;
        companyApplicationBatchApply({
          params: formValues.value,
          vika_doc_id: _form.vikaId
        })
          .then(() => {
            done();
            $msg.success('提交成功');
            emit('success');
            handleClose();
          })
          .finally(() => {
            instance.confirmButtonLoading = false;
          });
      }
    });
  } catch {
    step2Loading.value = false;
  }
}

// 初始化表单
watch(
  () => props.show,
  async val => {
    if (!val) return;
    await nextTick();
    DynamicsFormRef.value?.initFormList();
    step.value = 1;
    needInitVika.value = true;
  }
);
</script>

<style lang="scss" scoped></style>

<style lang="scss">
.vika-dialog {
  .el-dialog__body {
    max-height: initial !important;
  }
}
</style>
